package lazy_listview;



import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;


import org.json.JSONArray;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

public class JSONfunctions {
    public static JSONObject getJSONfromURL(String url) {
        
    	
    	JSONObject result = null;
		try {
			URL mUrl = new URL(url);
			URLConnection connection = mUrl.openConnection();
			//connection.setRequestProperty("Authorization", "Basic " + Common.authorization(UrlAPI.AUTHORIZATION_SERVER));
			/*connection.setRequestProperty("X_EMAIL", UserProfileDTO.email);
			connection.setRequestProperty("X_PASSWORD", UserProfileDTO.password);*/
			
			connection.setRequestProperty("Accept-Charset", "UTF-8");
			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();

			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			result = new JSONObject(builder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
    	
    }
    public static JSONObject getDataNoAcc(String url) {
		JSONObject result = null;
		try {
			URL mUrl = new URL(url);
			URLConnection connection = mUrl.openConnection();
			//connection.setRequestProperty("Authorization", "Basic " + Common.authorization(UrlAPI.AUTHORIZATION_SERVER));
			connection.setRequestProperty("Accept-Charset", "UTF-8");
			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();

			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			result = new JSONObject(builder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	public static JSONObject getDataWithAcc(String url) {
		JSONObject result = null;
		try {
			URL mUrl = new URL(url);
			URLConnection connection = mUrl.openConnection();
			//connection.setRequestProperty("Authorization", "Basic " + Common.authorization(UrlAPI.AUTHORIZATION_SERVER));
			//connection.setRequestProperty("X_EMAIL", Common.userLoginDTO.getEmail());
			//connection.setRequestProperty("X_PASSWORD", Common.userLoginDTO.getPassword());
			connection.setRequestProperty("Accept-Charset", "UTF-8");
			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.connect();

			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			System.out.println("chuoi builder:"+builder);
			result = new JSONObject(builder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	 public static JSONObject executePost(String targetURL, String urlParameters)
	  {
	    URL url;
	    HttpURLConnection connection = null;  
	    try {
	      //Create connection
	      url = new URL(targetURL);
	      
	      connection = (HttpURLConnection) url.openConnection();
	      connection.setRequestMethod("POST");
          //connection.addRequestProperty("Authorization", "Basic " + Common.authorization(UrlAPI.AUTHORIZATION_SERVER));
	      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
	      connection.setUseCaches (false);
	      connection.setDoInput(true);
	      connection.setDoOutput(true);
	      connection.connect();
	      
	      //Send request
	      DataOutputStream wr = new DataOutputStream (
	                  connection.getOutputStream ());
	      wr.writeBytes (urlParameters);
	      wr.flush ();
	      wr.close ();

	      //Get Response	
	      InputStream is = connection.getInputStream();
	      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	      String line;
	      StringBuffer response = new StringBuffer(); 
	      while((line = rd.readLine()) != null) {
	        response.append(line);
	        response.append('\r');
	      }
	      rd.close();
	      return new JSONObject(response.toString());

	    } catch (Exception e) {

	      e.printStackTrace();
	      return null;

	    } finally {

	      if(connection != null) {
	        connection.disconnect(); 
	      }
	    }
	  }
	 
	 
	public static String executePostParam(String targetURL, String urlParameters) {
	    URL url;
	    HttpURLConnection connection = null; 
	    try {
		  //Create connection
	    	url = new URL(targetURL);
	    	connection = (HttpURLConnection) url.openConnection();
	    	connection.setRequestMethod("POST");
	    	
	    	//connection.addRequestProperty("Authorization", "Basic " + Common.authorization(UrlAPI.AUTHORIZATION_SERVER));
	    	//connection.addRequestProperty("X_EMAIL", Common.userLoginDTO.getEmail());
	    	//connection.addRequestProperty("X_PASSWORD",Common.userLoginDTO.password);
	    	connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
	    	connection.setUseCaches (false);
	    	connection.setDoInput(true);
	    	connection.setDoOutput(true);
	    	connection.connect();
	    	//Send request
	    	DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
	    	wr.writeBytes (urlParameters);
	    	wr.flush ();
	    	wr.close ();
		
	    	//Get Response	
	    	InputStream is = connection.getInputStream();
	    	BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    	String line;
	    	StringBuffer response = new StringBuffer(); 
	    	while((line = rd.readLine()) != null) {
	    		response.append(line);
	    		response.append('\r');
	    	}
	    	rd.close();
	    	return response.toString();
	    } catch (Exception e) {
	    	e.printStackTrace();
	    	return null;

	    } finally {
	    	if(connection != null) {
	    		connection.disconnect(); 
	    	}
	    }
	}
	
	
	public static String executePostResourceStream(String nodeId, Bitmap bitmap){
		
		return null;
	}
	
	
	
	/*
	 * Convert from bitmap to File for upload
	 * 
	 */
	public static File getFilePath(Bitmap bm) {
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		
		Log.i("ImageUtil", "extStorageDirectory: " + extStorageDirectory);
		OutputStream outStream = null;
		File file = new File(extStorageDirectory, "c12xcxcxccvcx" + "." + "JPEG");
		try {
			outStream = new FileOutputStream(file);
			bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
			try {
				outStream.flush();
				outStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return file;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	public static String executePostNoParam(String targetURL)
	  {
	    URL url;
	    HttpURLConnection connection = null;  
	    try {
	      //Create connection
	      url = new URL(targetURL);
	      connection = (HttpURLConnection) url.openConnection();
	      connection.setRequestMethod("POST");
	      //connection.addRequestProperty("Authorization", "Basic " + Common.authorization(UrlAPI.AUTHORIZATION_SERVER));
	      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
	      connection.setUseCaches (false);
	      connection.setDoInput(true);
	      connection.setDoOutput(true);
	      connection.connect();
	      
	      //Send request
	      DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
	      wr.writeBytes("");
	      wr.flush ();
	      wr.close ();

	      //Get Response	
	      InputStream is = connection.getInputStream();
	      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	      String line;
	      StringBuffer response = new StringBuffer(); 
	      while((line = rd.readLine()) != null) {
	        response.append(line);
	        response.append('\r');
	      }
	      rd.close();
	      return response.toString();

	    } catch (Exception e) {

	      e.printStackTrace();
	      return null;

	    } finally {

	      if(connection != null) {
	        connection.disconnect(); 
	      }
	    }
	  }
	/**
	*
	* 
	* @author: truong.le
	* @datetime: Dec 10, 2013 8:50:48 AM
	* @return: JSONObject
	* @param isPost: true -- execute with method POST / false -- execute with method GET
	* @param targetURL: ULR of webservice
	* @param urlParameters: Parameters of webservice, if no put "" in  urlParameters
	* @param isAuthorization: need authorization, if true --> need authorization , false --> no need
	* @returnTODO
	* 
	*/
	public static JSONObject executeUrlWithOption(boolean isPost ,String targetURL, String urlParameters, boolean isAuthorization) {
		JSONObject jsResult = null;
	    URL url;
	    HttpURLConnection connection = null; 
	    try {
		  //Create connection
	    	url = new URL(targetURL);
	    	connection = (HttpURLConnection) url.openConnection();
	    	if(isPost)
	    		connection.setRequestMethod("POST");
	    	else
	    		connection.setRequestMethod("GET");
	    	if(isAuthorization)
	    	{
	    		//connection.addRequestProperty("Authorization", "Basic " + Common.authorization(UrlAPI.AUTHORIZATION_SERVER));
//	    		connection.addRequestProperty("Access-Token", Common.TOKEN_STRING);
		    	//connection.addRequestProperty("Access-Token", Common.userLoginDTO.getToken());
	    	}
	    	connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	    	connection.setRequestProperty("Accept-Charset", "UTF-8");
			connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5");

	    	connection.setUseCaches (false);
	    	connection.setDoInput(true);
	    	connection.setDoOutput(true);
	    	connection.connect();
	    	
	    	if(!urlParameters.equals(""))
	    	{
	    		//Send request
		    	DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
		    	wr.writeBytes (urlParameters);
		    	wr.flush ();
		    	wr.close ();
	    	}
	    	//Get Response	
	    	InputStream is = connection.getInputStream();
	    	BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	    	String line;
	    	StringBuffer response = new StringBuffer(); 
	    	while((line = rd.readLine()) != null) {
	    		response.append(line);
	    		response.append('\r');
	    	}
	    	rd.close();
	    	jsResult = new JSONObject(response.toString());
	    	return jsResult;
	    } catch (Exception e) {
	    	e.printStackTrace();
	    	return null;

	    } finally {
	    	if(connection != null) {
	    		connection.disconnect(); 
	    	}
	    }
	}
}